package ace.cmp.spring.data.jdbc.querydsl.core;

import com.google.common.base.CaseFormat;
import com.querydsl.sql.RelationalPathBase;
import org.springframework.util.ReflectionUtils;

/**
 * @author caspar
 * @date 2023/4/14 11:39
 */
public final class QuerydslUtils {

  public static RelationalPathBase<?> getRelationalPathBaseFromEntityType(Class<?> entityType) {
    Class queryClass = getQueryClass(entityType);
    return getRelationalPathBaseFromQueryClass(queryClass);
  }

  public static Class<?> getQueryClass(Class<?> entityType) {
    var fullName = entityType.getPackage().getName() + ".Q" + entityType.getSimpleName();
    try {
      return entityType.getClassLoader().loadClass(fullName);
    } catch (ClassNotFoundException e) {
      throw new IllegalArgumentException("Unable to load class " + fullName);
    }
  }

  public static RelationalPathBase<?> getRelationalPathBaseFromQueryClass(Class<?> queryClass) {
    var fieldName =
        CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, queryClass.getSimpleName().substring(1));
    var field = ReflectionUtils.findField(queryClass, fieldName);

    if (field == null) {
      throw new IllegalArgumentException(
          "Did not find a static field of the same type in " + queryClass);
    }

    return (RelationalPathBase<?>) ReflectionUtils.getField(field, null);
  }
}
